package com.chuantou.yuba.ui.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.NetworkImageView;
import com.chuantou.yuba.R;
import com.chuantou.yuba.api.RequestManager;
import com.chuantou.yuba.api.UriHelper;
import com.chuantou.yuba.api.request.BaseGsonRequest;
import com.chuantou.yuba.api.request.GsonRequest;
import com.chuantou.yuba.api.to.BaseTO;
import com.chuantou.yuba.api.to.FriendDataTO;
import com.chuantou.yuba.api.to.FriendTO;
import com.chuantou.yuba.api.to.UserTO;
import com.chuantou.yuba.ui.LoginActivity;
import com.chuantou.yuba.ui.widget.LoadingView.Style;
import com.chuantou.yuba.util.AccountManager;
import com.chuantou.yuba.util.ActivityHelper;
import com.chuantou.yuba.util.BitmapBinder;
import com.chuantou.yuba.util.Constants;
import com.chuantou.yuba.util.UiUtil;
import com.chuantou.yuba.util.ViewHolder;

public class BlackListFragment extends PaginationListFragment<FriendDataTO> {
	private BlackListAdapter mAdapter;
	private boolean mNeedRefresh = true;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext.registerReceiver(mBlackListChangedReceiver, new IntentFilter(Constants.INTENT_ACITON_BLACK_LIST_CHANGED));
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View contentView = super.onCreateView(inflater, container, savedInstanceState);
		if (mAdapter == null) {
			mAdapter = new BlackListAdapter();
			mListView.setAdapter(mAdapter);
			mListView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
					Object obj = parent.getItemAtPosition(position);
					if (obj != null && obj instanceof FriendTO) {
						FriendTO friend = (FriendTO) obj;
						ActivityHelper.toProfileActivity(getActivity(), friend.getUid());
					}
				}
			});
			registerForContextMenu(mListView);
		}
		return contentView;
	}

	@Override
	public void onResume() {
		super.onResume();
		if (mNeedRefresh) {
			load(1);
		}
	}

	@Override
	public void onDestroy() {
		mContext.unregisterReceiver(mBlackListChangedReceiver);
		super.onDestroy();
	}

	private BroadcastReceiver mBlackListChangedReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			mNeedRefresh = true;
		}

	};

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		getActivity().getMenuInflater().inflate(R.menu.menu_remove_black_list, menu);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		if (item.getItemId() == R.id.menu_remove) {
			FriendTO friendTO = (FriendTO) mAdapter.getItem(((AdapterContextMenuInfo) item.getMenuInfo()).position - 1);
			removeBlackList(friendTO);
			return true;
		}
		return super.onContextItemSelected(item);
	}

	@Override
	protected BaseGsonRequest<FriendDataTO> getRequest(Listener<FriendDataTO> listener, ErrorListener errorListener) {
		String url = UriHelper.getBlackListUrl();
		HashMap<String, String> params = new HashMap<String, String>();
		UserTO user = AccountManager.getInstance(mContext).getUserTO();
		params.put(UriHelper.PARAMS_UID, user != null ? String.valueOf(user.getUid()) : "0");
		params.put(UriHelper.PARAMS_PAGE_SIZE, String.valueOf(Constants.DEFAULT_PAGE_SIZE));
		params.put(UriHelper.PARAMS_PAGE_NO, String.valueOf(1));
		GsonRequest<FriendDataTO> request = new GsonRequest<FriendDataTO>(Method.POST, url, listener, errorListener, params, FriendDataTO.class);
		return request;
	}

	@Override
	public void onResponse(FriendDataTO response) {
		if (getActivity() != null) {
			mNeedRefresh = false;
			super.onResponse(response);
			if (response != null) {
				List<FriendTO> friends = response.getFriends();
				// 第一页
				if (response.getCurrentPage() <= 1) {
					// 保存到本地数据库缓存
					mAdapter.clear();
				}
				mAdapter.add(friends);
				mLoadingView.setStyle(Style.EMPTY, getEmptyString());
			} else {
				mLoadingView.setStyle(Style.EMPTY, getEmptyString());
			}
			mAdapter.notifyDataSetChanged();
		}
	}

	@Override
	protected String getEmptyString() {
		return getString(R.string.no_content);
	}

	public void removeBlackList(final FriendTO friendTO) {
		AccountManager accountManager = AccountManager.getInstance(mContext);
		if (!accountManager.isLogined()) {
			UiUtil.showNoLoginDialog(getActivity(), -1, LoginActivity.ACTION_RETURN);
			return;
		} else {
			UserTO user = accountManager.getUserTO();
			if (user.isExpired()) {
				Toast.makeText(mContext, R.string.message_token_expired, Toast.LENGTH_SHORT).show();
				LoginActivity.start(getActivity(), -1, LoginActivity.ACTION_RETURN);
			} else {
				String url = UriHelper.getRemoveBlackListUrl();
				HashMap<String, String> params = new HashMap<String, String>();
				params.put(UriHelper.PARAMS_TOKEN, user.getToken());
				params.put(UriHelper.PARAMS_MATCH_ID, String.valueOf(friendTO.getUid()));
				params.put(UriHelper.PARAMS_UID, String.valueOf(user.getUid()));
				GsonRequest<BaseTO> request = new GsonRequest<BaseTO>(Method.POST, url, new Listener<BaseTO>() {

					@Override
					public void onResponse(BaseTO response) {
						if (getActivity() != null) {
							if (response != null) {
								if (response.isSuccess()) {
									Toast.makeText(mContext, R.string.operate_success, Toast.LENGTH_SHORT).show();
									mAdapter.remove(friendTO);
									mAdapter.notifyDataSetChanged();
								} else {
									if (response.getStatus() == BaseTO.STATUS_TOKEN_ERROR || response.getStatus() == BaseTO.STATUS_TOKEN_EXPIRED) {
										Toast.makeText(mContext, R.string.message_token_expired, Toast.LENGTH_SHORT).show();
										LoginActivity.start(getActivity(), -1, LoginActivity.ACTION_RETURN);
									} else {
										String msg = response.getMsg();
										msg = TextUtils.isEmpty(msg) ? mContext.getString(R.string.operate_failed) : msg;
										Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
									}
								}
							} else {
								Toast.makeText(mContext, R.string.operate_failed, Toast.LENGTH_SHORT).show();
							}
						}
					}
				}, new ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {
						if (getActivity() != null) {
							Toast.makeText(mContext, R.string.request_error, Toast.LENGTH_SHORT).show();
						}
					}
				}, params, BaseTO.class);
				RequestManager.startRequest(mContext, request);
			}
		}
	}

	class BlackListAdapter extends BaseAdapter {
		private List<FriendTO> mList = new ArrayList<FriendTO>();

		public void add(FriendTO to) {
			mList.add(to);
		}

		public void add(List<FriendTO> list) {
			if (list != null && !list.isEmpty()) {
				mList.addAll(list);
			}
		}

		public void clear() {
			mList.clear();
		}

		@Override
		public int getCount() {
			return mList.size();
		}

		public void remove(FriendTO to) {
			mList.remove(to);
		}

		@Override
		public Object getItem(int position) {
			return mList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = View.inflate(mContext, R.layout.black_list_item, null);
			}
			FriendTO friendTO = mList.get(position);
			NetworkImageView avatarView = ViewHolder.get(convertView, R.id.avatar);
			BitmapBinder.bindCircularNetImage(mContext, avatarView, friendTO.getAvatar(), R.drawable.default_avatar_round_small);
			TextView nicknameView = ViewHolder.get(convertView, R.id.nickname);
			nicknameView.setText(friendTO.getNickname());
			return convertView;
		}
	}

}
